import Vue from "vue";

var VueEvent = new Vue();

// 在 VueEvent 中定义全局数据
VueEvent.sharedData = Vue.observable({
	measured_acceleration_y: [],
	measured_acceleration_x: [],
	measured_acceleration_z: [],
	// angular_velocity_y: [],
	// angular_velocity_x: [],
	// angular_velocity_z: [],
	correct_acceleration: [], //修正后的加速度
	tempx: [],
	tempy: [],
	tempz: [],
	tempa: [],
	tempb: [],
	tempc: [],
	gravityX: 0,
	gravityY: 0,
	gravityZ: 0,
	// 设备方向
	alpha: [],
	beta: [],
	gamma: [],

	maxDataLength: 10000, // 定义数组最大长度
	clock: ["", "", "", ""],
	isMuted: false, // 🚀 是否静音（默认 false）
	action: "深蹲",
	pinlv: 300,
	aim: "增肌",
	map_action: {
		0: "深蹲",
		1: "卧推",
		2: "硬拉",
		3: "俯身划船",
		4: "高翻",
		5: "站姿推肩",
		6: "高位下拉",
		7: "坐姿推肩",
		8: "罗马尼亚硬拉",
		9: "直腿硬拉"
	},
	train_record: [

	],
	train_id: 0,
});


VueEvent.xyz_to_y = function(measured_acceleration_x, measured_acceleration_y, measured_acceleration_z, alpha, beta,
	gamma) {
	// 计算当前最小长度
	let minLength = Math.min(
		measured_acceleration_x.length,
		measured_acceleration_y.length,
		measured_acceleration_z.length,
		alpha.length,
		beta.length,
		gamma.length
	);

	// 截取所有数组，确保它们的长度一致
	measured_acceleration_x = measured_acceleration_x.slice(0, minLength);
	measured_acceleration_y = measured_acceleration_y.slice(0, minLength);
	measured_acceleration_z = measured_acceleration_z.slice(0, minLength);
	alpha = alpha.slice(0, minLength);
	beta = beta.slice(0, minLength);
	gamma = gamma.slice(0, minLength);
	// console.log("measured_acceleration_x",measured_acceleration_x);
	// console.log("measured_acceleration_y",measured_acceleration_x);
	// console.log("measured_acceleration_z",measured_acceleration_x);
	// console.log("alpha",alpha);
	// console.log("beta",beta);
	// console.log("gamma",gamma);
	let current_acceleration = [];
	for (let i = 0; i < minLength; i++) {
		let temp_data = parseFloat(VueEvent.one_xyz_to_y(measured_acceleration_x[i], measured_acceleration_y[i],
			measured_acceleration_z[i], alpha[i], beta[i], gamma[i]).toFixed(7));
		current_acceleration.push(temp_data);
	}
	return current_acceleration;
}


// 修正加速度
VueEvent.one_xyz_to_y = function(measured_acceleration_x, measured_acceleration_y, measured_acceleration_z, alpha, beta,
	gamma) {

	const deviceX = measured_acceleration_x * 9.8;
	const deviceY = measured_acceleration_y * 9.8;
	const deviceZ = measured_acceleration_z * 9.8;
	// console.log("deviceX",deviceX);
	// console.log("deviceY",deviceY);
	// console.log("deviceZ",deviceZ);
	// let { gravityX, gravityY, gravityZ } = VueEvent.sharedData;
	let gravityX = VueEvent.sharedData.gravityX;
	let gravityY = VueEvent.sharedData.gravityY;
	let gravityZ = VueEvent.sharedData.gravityZ;

	let filter_alpha = 0.75; // 滤波系数
	// console.log("gravityX",gravityX);
	// console.log("gravityY",gravityY);
	// console.log("gravityZ",gravityZ);
	if (gravityX === 0 && gravityY === 0 && gravityZ === 0) {
		// console.log("first")
		gravityX = deviceX;
		gravityY = deviceY;
		gravityZ = deviceZ;
	} else {
		// console.log("second")
		gravityX = filter_alpha * gravityX + (1 - filter_alpha) * deviceX;
		gravityY = filter_alpha * gravityY + (1 - filter_alpha) * deviceY;
		gravityZ = filter_alpha * gravityZ + (1 - filter_alpha) * deviceZ;
	}

	VueEvent.sharedData.gravityX = gravityX;
	VueEvent.sharedData.gravityY = gravityY;
	VueEvent.sharedData.gravityZ = gravityZ;
	// console.log("gravityX",gravityX);
	// console.log("gravityY",gravityY);
	// console.log("gravityZ",gravityZ);
	const alphaRad = alpha * Math.PI / 180;
	const betaRad = beta * Math.PI / 180;
	const gammaRad = gamma * Math.PI / 180;
	// console.log("alphaRad",alphaRad);
	// console.log("betaRad",betaRad);
	// console.log("gammaRad",gammaRad);
	const gravityMagnitude = Math.sqrt(gravityX ** 2 + gravityY ** 2 + gravityZ ** 2);
	const gx = gravityX / gravityMagnitude;
	const gy = gravityY / gravityMagnitude;
	const gz = gravityZ / gravityMagnitude;
	// console.log("gx",gx);
	// console.log("gy",gy);
	// console.log("gz",gz);
	const worldY_axis = [-gx, -gy, -gz];

	const tempNorth = [Math.sin(alphaRad) * Math.cos(betaRad), -Math.cos(alphaRad) * Math.cos(betaRad), Math.sin(
		betaRad)];
	// console.log("tempNorth",tempNorth);
	const dotProduct = tempNorth[0] * gx + tempNorth[1] * gy + tempNorth[2] * gz;
	let northX_ortho = tempNorth[0] - dotProduct * gx;
	let northY_ortho = tempNorth[1] - dotProduct * gy;
	let northZ_ortho = tempNorth[2] - dotProduct * gz;

	const normNorth = Math.sqrt(northX_ortho ** 2 + northY_ortho ** 2 + northZ_ortho ** 2);
	northX_ortho /= normNorth;
	northY_ortho /= normNorth;
	northZ_ortho /= normNorth;
	// console.log("northX_ortho",northX_ortho);
	// console.log("northY_ortho",northY_ortho);
	// console.log("northZ_ortho",northZ_ortho);
	const worldX_axis = [
		worldY_axis[1] * northZ_ortho - worldY_axis[2] * northY_ortho,
		worldY_axis[2] * northX_ortho - worldY_axis[0] * northZ_ortho,
		worldY_axis[0] * northY_ortho - worldY_axis[1] * northX_ortho
	];
	// console.log("worldX_axis",worldX_axis);
	const R = [
		worldX_axis,
		worldY_axis,
		[northX_ortho, northY_ortho, northZ_ortho]
	];
	// console.log("R",R);
	const linearX = deviceX;
	const linearY = deviceY;
	const linearZ = deviceZ;
	// console.log("linearX",linearX);
	// console.log("linearY",linearY);
	// console.log("linearZ",linearZ);
	const worldX = R[0][0] * linearX + R[0][1] * linearY + R[0][2] * linearZ;
	const worldY = R[1][0] * linearX + R[1][1] * linearY + R[1][2] * linearZ;
	const worldZ = R[2][0] * linearX + R[2][1] * linearY + R[2][2] * linearZ;
	// console.log("worldX",worldX);
	// console.log("worldY",worldY);
	// console.log("worldZ",worldZ);
	const adjustedWorldY = -worldY;
	// console.log("adjustedWorldY",adjustedWorldY);
	return adjustedWorldY;

};


// 🚀 切换静音状态的方法
VueEvent.changeVoice = function() {
	VueEvent.sharedData.isMuted = !VueEvent.sharedData.isMuted;
	// console.log("静音状态已变更:", VueEvent.sharedData.isMuted);
};
VueEvent.add_aim = function(s) {
	VueEvent.sharedData.aim = s;
}
VueEvent.add_action = function(s) {
	VueEvent.sharedData.action = s;
}
// ✅ 初始化语音
VueEvent.init_Clock_Audio = function() {
	VueEvent.textToVoice("三", 0);
	VueEvent.textToVoice("二", 1);
	VueEvent.textToVoice("一", 2);
	VueEvent.textToVoice("开始", 3);
};

// ✅ 文字转语音
VueEvent.textToVoice = function(text, index) {
	var pluginSI = requirePlugin("WechatSI");
	var innerAudioSI = wx.createInnerAudioContext();
	pluginSI.textToSpeech({
		lang: "zh_CN",
		tts: true,
		content: text,
		success: function(res) {
			console.log("succ tts", res.filename);
			VueEvent.sharedData.clock[index] = res.filename;
			innerAudioSI.src = res.filename;
			// innerAudioSI.play();
			innerAudioSI.onEnded(() => {
				console.log("语音播放完毕");
				innerAudioSI.stop();
				innerAudioSI.destroy();
			});
		},
		fail: function(res) {
			console.log("fail tts", res);
		}
	});
};

// ✅ 初始化加速度数据
VueEvent.init_Accelerometer = function() {
	VueEvent.sharedData.measured_acceleration_x = [];
	VueEvent.sharedData.measured_acceleration_y = [];
	VueEvent.sharedData.measured_acceleration_z = [];
	// VueEvent.sharedData.angular_velocity_x = [];
	// VueEvent.sharedData.angular_velocity_y = [];
	// VueEvent.sharedData.angular_velocity_z = [];
	VueEvent.sharedData.alpha = [];
	VueEvent.sharedData.beta = [];
	VueEvent.sharedData.gamma = [];
};

// ✅ 删除部分加速度数据
VueEvent.del_Accelerometer = function(index) {
	VueEvent.sharedData.measured_acceleration_x = VueEvent.sharedData.measured_acceleration_x.slice(index);
	VueEvent.sharedData.measured_acceleration_y = VueEvent.sharedData.measured_acceleration_y.slice(index);
	VueEvent.sharedData.measured_acceleration_z = VueEvent.sharedData.measured_acceleration_z.slice(index);
	// VueEvent.sharedData.angular_velocity_x = VueEvent.sharedData.angular_velocity_x.slice(index);
	// VueEvent.sharedData.angular_velocity_y = VueEvent.sharedData.angular_velocity_y.slice(index);
	// VueEvent.sharedData.angular_velocity_z = VueEvent.sharedData.angular_velocity_z.slice(index);


	VueEvent.sharedData.alpha = VueEvent.sharedData.alpha.slice(index);
	VueEvent.sharedData.beta = VueEvent.sharedData.beta.slice(index);
	VueEvent.sharedData.gamma = VueEvent.sharedData.gamma.slice(index);
};

// ✅ 开始监听加速度和陀螺仪
VueEvent.startListeningAccelerometer = function() {
	console.log("开启全局监听手机加速度和角速度");

	uni.startAccelerometer({
		interval: "game",
		success: () => {
			uni.onAccelerometerChange((res) => {
				if (VueEvent.sharedData.measured_acceleration_x.length >= VueEvent.sharedData
					.maxDataLength) {
					VueEvent.sharedData.measured_acceleration_x.shift();
					VueEvent.sharedData.measured_acceleration_y.shift();
					VueEvent.sharedData.measured_acceleration_z.shift();
				}
				VueEvent.sharedData.measured_acceleration_x.push(parseFloat(res.x.toFixed(7)));
				VueEvent.sharedData.measured_acceleration_y.push(parseFloat(res.y.toFixed(7)));
				VueEvent.sharedData.measured_acceleration_z.push(parseFloat(res.z.toFixed(7)));

				// VueEvent.sharedData.tempx = parseFloat(res.x.toFixed(7)) ;
				// VueEvent.sharedData.tempy = parseFloat(res.y.toFixed(7)) ;
				// VueEvent.sharedData.tempz = parseFloat(res.z.toFixed(7)) ;
			});
		},
		fail: (err) => {
			console.error("启动加速度传感器失败：", err);
		}
	});

	// uni.startGyroscope({
	//     interval: "game",
	//     success: () => {
	//         uni.onGyroscopeChange((res) => {
	//             if (VueEvent.sharedData.angular_velocity_x.length >= VueEvent.sharedData.maxDataLength) {
	//                 VueEvent.sharedData.angular_velocity_x.shift();
	//                 VueEvent.sharedData.angular_velocity_y.shift();
	//                 VueEvent.sharedData.angular_velocity_z.shift();
	//             }
	//             VueEvent.sharedData.angular_velocity_x.push(parseFloat(res.x.toFixed(7)));
	//             VueEvent.sharedData.angular_velocity_y.push(parseFloat(res.y.toFixed(7)));
	//             VueEvent.sharedData.angular_velocity_z.push(parseFloat(res.z.toFixed(7)));


	//         });
	//     },
	//     fail: (err) => {
	//         console.error("启动陀螺仪传感器失败：", err);
	//     }
	// });

	// ✅ 设备方向监听
	uni.startDeviceMotionListening({
		interval: 'game',
		success: () => {
			uni.onDeviceMotionChange((res) => {
				// console.log("获取到设备方向相关数据");
				if (VueEvent.sharedData.alpha.length >= VueEvent.sharedData.maxDataLength) {
					VueEvent.sharedData.alpha.shift();
					VueEvent.sharedData.beta.shift();
					VueEvent.sharedData.gamma.shift();
				}
				VueEvent.sharedData.alpha.push(res.alpha);
				VueEvent.sharedData.beta.push(res.beta);
				VueEvent.sharedData.gamma.push(res.gamma);

				// console.log("alpha",res.alpha);
				// console.log("beta",res.beta);
				// console.log("gamma",res.gamma);

			});
		},
		fail: (err) => {
			console.error('设备方向监听失败:', err);
		}
	});
	// VueEvent.init_Accelerometer();
};


// ✅ 停止监听加速度、陀螺仪和设备方向
VueEvent.stopListeningAccelerometer = function() {
	console.log("停止全局监听手机加速度、角速度和设备方向");

	uni.stopAccelerometer({
		success: () => {
			console.log("成功停止加速度传感器监听");
		},
		fail: (err) => {
			console.error("停止加速度传感器监听失败：", err);
		}
	});

	// uni.stopGyroscope({
	//     success: () => {
	//         console.log("成功停止陀螺仪传感器监听");
	//     },
	//     fail: (err) => {
	//         console.error("停止陀螺仪传感器监听失败：", err);
	//     }
	// });

	// ✅ 停止设备方向监听
	uni.stopDeviceMotionListening({
		success: () => {
			console.log("成功停止设备方向监听");
		},
		fail: (err) => {
			console.error("停止设备方向监听失败：", err);
		}
	});

	// ✅ 解绑回调函数，防止后续数据干扰
	uni.offAccelerometerChange();
	// uni.offGyroscopeChange();
	uni.offDeviceMotionChange(); // 解绑设备方向回调

	// ✅ 重新初始化所有数据
	VueEvent.init_Accelerometer();
};


export default VueEvent;